package study.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.http.client.HttpClient;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author sunxuejian
 * @version 1.0
 * @date 2020/3/12 19:05
 */
@SpringBootConfiguration
@ConditionalOnClass(RestTemplate.class)
public class RestTemplateAutoConfig {

	@Bean
	@LoadBalanced
	public RestTemplate restTemplate(HttpClient httpClient) {

		RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));

		List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters().stream().filter((item) -> {
			return (item.getClass() != StringHttpMessageConverter.class && item.getClass() != MappingJackson2HttpMessageConverter.class);
		}).collect(Collectors.toList());
		httpMessageConverters.add(new StringHttpMessageConverter(Charset.forName("utf-8")));

		//fastJson
		FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
		SerializerFeature[] serializerFeatures = {
				//    数值字段如果为null，则输出为0
				SerializerFeature.WriteNullNumberAsZero,
				//     List字段如果为null,输出为[],而非null
				SerializerFeature.WriteNullListAsEmpty,
				//    字符类型字段如果为null,输出为"",而非null
				SerializerFeature.WriteNullStringAsEmpty,
				//    Boolean字段如果为null,输出为false,而非null
				SerializerFeature.WriteNullBooleanAsFalse,
		};
//		fastJsonHttpMessageConverter.setFeatures(serializerFeatures);
		fastJsonHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(
				MediaType.APPLICATION_JSON,
				MediaType.APPLICATION_JSON_UTF8,
				new MediaType("application", "*+json")));
		httpMessageConverters.add((HttpMessageConverter)fastJsonHttpMessageConverter);

		restTemplate.setMessageConverters(httpMessageConverters);
		return restTemplate;
	}

}
